package org.linlinjava.litemall.wx.web;

import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.wx.annotation.LoginUser;
import org.linlinjava.litemall.wx.service.WxStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 商品服务
 */
@RestController
@RequestMapping("/wx/store")
@Validated
public class WxStoreController {
	private final Log logger = LogFactory.getLog(WxStoreController.class);

	@Autowired
	private LitemallStoreService goodsService;

	@Autowired
	private LitemallGoodsProductService productService;

	@Autowired
	private LitemallIssueService goodsIssueService;

	@Autowired
	private LitemallGoodsAttributeService goodsAttributeService;

	@Autowired
	private LitemallBrandService brandService;

	@Autowired
	private LitemallCommentService commentService;

	@Autowired
	private LitemallUserService userService;

	@Autowired
	private LitemallCollectService collectService;

	@Autowired
	private LitemallFootprintService footprintService;

	@Autowired
	private LitemallCategoryService categoryService;

	@Autowired
	private LitemallSearchHistoryService searchHistoryService;

	@Autowired
	private LitemallGoodsSpecificationService goodsSpecificationService;

	@Autowired
	private LitemallGrouponRulesService rulesService;

	private final static ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(9);

	private final static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

	private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(16, 16, 1000, TimeUnit.MILLISECONDS, WORK_QUEUE, HANDLER);


	@Autowired
	private LitemallStoreService storeService;

	@Autowired
	private WxStoreService wxStoreService;



	/**
	 * 商品详情
	 * <p>
	 * 用户可以不登录。
	 * 如果用户登录，则记录用户足迹以及返回用户收藏信息。
	 *
	 * @param userId 用户ID
	 * @param id     商品ID
	 * @return 商品详情
	 */
	@GetMapping("detail")
	public Object detail(@LoginUser Integer userId, @NotNull Integer id) {
		// 商品信息
		LitemallStore info = storeService.findById(id);

		List<StoreCategoryVo> storeCategoryVoList = wxStoreService.findCategoryVoList(id);

		// 评论
//		Callable<Map> commentsCallable = () -> {
//			List<LitemallComment> comments = commentService.queryGoodsByGid(id, 0, 2);
//			List<Map<String, Object>> commentsVo = new ArrayList<>(comments.size());
//			long commentCount = PageInfo.of(comments).getTotal();
//			for (LitemallComment comment : comments) {
//				Map<String, Object> c = new HashMap<>();
//				c.put("id", comment.getId());
//				c.put("addTime", comment.getAddTime());
//				c.put("content", comment.getContent());
//				c.put("adminContent", comment.getAdminContent());
//				LitemallUser user = userService.findById(comment.getUserId());
//				c.put("nickname", user == null ? "" : user.getNickname());
//				c.put("avatar", user == null ? "" : user.getAvatar());
//				c.put("picList", comment.getPicUrls());
//				commentsVo.add(c);
//			}
//			Map<String, Object> commentList = new HashMap<>();
//			commentList.put("count", commentCount);
//			commentList.put("data", commentsVo);
//			return commentList;
//		};


		// 用户收藏


		// 记录用户的足迹 异步处理


		Map<String, Object> data = new HashMap<>();

		try {
			data.put("info", info);
			data.put("storeCategoryVoList", storeCategoryVoList);
		}
		catch (Exception e) {
			e.printStackTrace();
		}

		//商品分享图片地址
		data.put("shareImage", "test");
		return ResponseUtil.ok(data);
	}


	/***
	 * 检查是否有可订座位
	 * http://localhost:8082/wx/store/checkSeat?storeId=15&type=%E5%8C%85%E9%97%B4&range=1-20&preference=%E9%9D%A0%E7%AA%97&orderRange=1
	 * @param userId
	 * @param type
	 * @param storeId
	 * @param orderTime
	 * @param orderRange
	 * @return
	 */
	@GetMapping("checkSeat")
	public Object detail(@LoginUser Integer userId,  String type, Integer seatId, @NotNull Integer storeId, String orderTime,Integer orderRange) {
		Map<String, Object> data = new HashMap<>();
		try {
			seatId = wxStoreService.checkSeat(userId,type,seatId,storeId,orderTime,orderRange);
			data.put("seatId", seatId);
		}
		catch (Exception e) {
			e.printStackTrace();
		}

		return ResponseUtil.ok(data);
	}


	/**
	 * 根据条件搜素商家
	 * <p>
	 * 1. 这里的前五个参数都是可选的，甚至都是空
	 * 2. 用户是可选登录，如果登录，则记录用户的搜索关键字
	 *
	 * @param keyword    关键字，可选
	 * @param userId     用户ID
	 * @param page       分页页数
	 * @param limit       分页大小
	 * @param sort       排序方式，支持"add_time", "retail_price"或"name"
	 * @param order      排序类型，顺序或者降序
	 * @return 根据条件搜素的商品详情
	 */
	@GetMapping("list")
	public Object list(
		String keyword,
		String tag,
		@LoginUser Integer userId,
		@RequestParam(defaultValue = "1") Integer page,
		@RequestParam(defaultValue = "10") Integer limit,
		@Sort(accepts = {"add_time", "retail_price", "name"}) @RequestParam(defaultValue = "add_time") String sort,
		@Order @RequestParam(defaultValue = "desc") String order) {

		//添加到搜索历史
		if (userId != null && !StringUtils.isEmpty(keyword)) {
			LitemallSearchHistory searchHistoryVo = new LitemallSearchHistory();
			searchHistoryVo.setKeyword(keyword);
			searchHistoryVo.setUserId(userId);
			searchHistoryVo.setFrom("wx");
			searchHistoryService.save(searchHistoryVo);
		}

		//查询列表数据
		List<LitemallStore> goodsList = storeService.querySelective(tag,keyword,  page, limit, sort, order);

		// 查询商品所属类目列表。

		PageInfo<LitemallStore> pagedList = PageInfo.of(goodsList);

		Map<String, Object> entity = new HashMap<>();
		entity.put("list", goodsList);
		entity.put("total", pagedList.getTotal());
		entity.put("page", pagedList.getPageNum());
		entity.put("limit", pagedList.getPageSize());
		entity.put("pages", pagedList.getPages());
//		entity.put("filterCategoryList", categoryList);

		// 因为这里需要返回额外的filterCategoryList参数，因此不能方便使用ResponseUtil.okList
		return ResponseUtil.ok(entity);
	}


	@GetMapping("seatList")
	public Object seatList(
			@LoginUser Integer userId,  String type,  @NotNull Integer storeId, Integer orderRange) {
		//查询列表数据
		List<SeatVo> seatList = storeService.findSeatList(storeId,type,  orderRange);
		Map<String, Object> entity = new HashMap<>();
		entity.put("seatList", seatList);

		return ResponseUtil.ok(entity);
	}




}
